package com.ruoyi.web.controller.system;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.Filebyte;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.ProjectPicture;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ProjectFile;
import com.ruoyi.system.service.IProjectFileService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 项目附件Controller
 *
 * @author ruoyi
 * @date 2021-01-06
 */
@RestController
@RequestMapping("/system/file")
public class ProjectFileController extends BaseController {
    @Autowired
    private IProjectFileService projectFileService;

    /**
     * 查询项目附件列表
     */
//    @PreAuthorize("@ss.hasPermi('system:file:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProjectFile projectFile) {
        startPage();
        List<ProjectFile> list = projectFileService.selectProjectFileList(projectFile);
        return getDataTable(list);
    }

    /**
     * 获取项目附件详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:file:query')")
    @GetMapping(value = "/{pfilId}")
    public ProjectFile getInfo(@PathVariable("pfilId") Long pfilId) {
        return projectFileService.selectProjectFileById(pfilId);
    }

    /**
     * 新增项目附件
     */
//    @PreAuthorize("@ss.hasPermi('system:file:add')")
    @ApiOperation(value = "文件上传")
    @Log(title = "项目附件", businessType = BusinessType.INSERT)
    @PostMapping(value = "/upload")
    @CrossOrigin
    public AjaxResult fileUpload(@RequestParam(value = "file") MultipartFile file,
                                 @RequestParam(value = "bz") String bz,
                                Long userId,
                                 @RequestParam(value = "proId") Long proId) {
        try {
            String profile = RuoYiConfig.getProfile();
            byte[] bytes = file.getBytes();
            //文件夹
            Path path2 = Paths.get(profile+"//" + proId);
            //具体文件
            Path path = Paths.get(profile+"//" + proId + "//" + file.getOriginalFilename());
            File file1 = path.toFile();
            //创建文件夹
            if (!file1.exists()) {
                path2.toFile().mkdirs();
            }
            if (file1.isFile()) {
                return AjaxResult.error("文件上传失败,文件存在");
            } else {
                Files.write(path, bytes);//创建文件
                ProjectFile projectFile = new ProjectFile();
                projectFile.setFileName(file.getOriginalFilename());
                int a = bytes.length;
                double s = a / 1024;
                projectFile.setFileSize(s + "KB");
                projectFile.setPfilRemark(bz);
                projectFile.setProId(proId);
                projectFile.setUserId(userId);
                projectFile.setFileUrl(path.toString());
                int a1 = projectFileService.insertProjectFile(projectFile);
                if (a1 > 0) {
                    if (file1.isFile()) {
                        return AjaxResult.success("文件上传成功");
                    }else {
                        return AjaxResult.error("文件上传失败");
                    }

                } else {
                    if (file1.isFile()) {
                        file1.delete();
                    }
                    return AjaxResult.error("文件上传失败");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("文件上传失败");
        }
    }

    /**
     * 修改项目附件
     */
//    @PreAuthorize("@ss.hasPermi('system:file:edit')")
    @Log(title = "项目附件", businessType = BusinessType.UPDATE)
    @PutMapping
    @CrossOrigin
    @ApiOperation(value = "文件上传修改")
    public AjaxResult edit(
            MultipartFile file,
            @RequestParam(value = "bz") String bz,
            @RequestParam(value = "proId") Long proId,
            @RequestParam(value = "userId") Long userId,
            @RequestParam(value = "pfilId") Long pfilId) {
        String profile = RuoYiConfig.getProfile();
        if (file != null) {
            try {
                byte[] bytes = file.getBytes();
                //文件夹
                Path path2 = Paths.get(profile+"//" + proId);
                //具体文件
                Path path = Paths.get(profile+"//" + proId+ "//" + file.getOriginalFilename());
                File file1 = path.toFile();
                //没有文件夹创建
                if (!file1.exists()) {
                    path2.toFile().mkdirs();
                    File f= new File(path2.toString());
                    f.setWritable( true,  false);
                }
                //未修改数据
                ProjectFile projectFile1 = projectFileService.selectProjectFileById(pfilId);
                //判断路径和大小是否相同
                ProjectFile projectFile = new ProjectFile();
                projectFile.setFileName(file.getOriginalFilename());
                int a = bytes.length;
                double s = a / 1024;
                projectFile.setFileSize(s + "KB");
                projectFile.setPfilRemark(bz);
                projectFile.setProId(proId);
                projectFile.setPfilId(pfilId);
                projectFile.setUserId(userId);
                projectFile.setFileUrl(path.toString());
                new File(projectFile1.getFileUrl()).delete();//删除原本的文件
                Files.write(path, bytes);//写入新的文件
                projectFile.setFileName(file.getOriginalFilename());
                projectFile.setFileUrl(path.toString());
                if (projectFileService.updateProjectFile(projectFile) > 0) {
                    return AjaxResult.success("修改成功");
                } else {
                    return AjaxResult.error("修改失败");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return AjaxResult.error("文件修改失败");
            }
        } else {
            ProjectFile projectFile = new ProjectFile();
            projectFile.setPfilRemark(bz);
            projectFile.setPfilId(pfilId);
            projectFile.setProId(proId);
            if (projectFileService.updateProjectFile(projectFile) > 0) {
                return AjaxResult.success("修改成功");
            } else {
                return AjaxResult.error("修改失败");
            }
        }
    }
    /**
     * 删除项目附件
     */
//    @PreAuthorize("@ss.hasPermi('system:file:remove')")
    @Log(title = "项目附件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{pfilIds}")
    public AjaxResult remove(@PathVariable Long[] pfilIds) {
        return toAjax(projectFileService.deleteProjectFileByIds(pfilIds));
    }

    //图片上传
    @Log(title = "项目图片", businessType = BusinessType.INSERT)
    @PostMapping(value = "/picture/upload")
    @CrossOrigin
    public AjaxResult pictureUpload(MultipartFile file, Long proId) {
        try {
            String profile = RuoYiConfig.getProfile();
            byte[] bytes = file.getBytes();
            //文件夹
            Path path2 = Paths.get(profile+"//" + proId);
            //具体文件
            Path path = Paths.get(profile+"//" + proId+ "//" + file.getOriginalFilename());
            Path path1 = Paths.get("profile//" + proId + "//" + file.getOriginalFilename());
            File file1 = path.toFile();
            //创建文件夹
            if (!file1.exists()) {
                path2.toFile().mkdirs();
            }
            if (file1.isFile()) {
                String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                String replace = path1.toString().replace(suffixName, "(" + (int) (Math.random() * 10) + ")" + suffixName);

            }
            Files.write(path, bytes);//创建文件
            ProjectPicture projectFile = new ProjectPicture();
            projectFile.setPicName(file.getOriginalFilename());
            projectFile.setPicUrl(path1.toString());
            projectFile.setProId(proId);
            if (projectFileService.insertProjectPicture(projectFile) > 0) {
                return AjaxResult.success("文件上传成功");
            } else {
                if (file1.isFile()) {
                    file1.delete();
                }
                return AjaxResult.error("文件上传失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("文件上传失败");
        }
    }

    //图片下载
    @GetMapping("/picture/download")
    public void pictureDownload(HttpServletResponse response, Long picId) throws Exception {
        System.out.println("进");
        ProjectPicture projectFile = projectFileService.selectProjectPictureById(picId);
        String getFileUrl = projectFile.getPicUrl();
        String profile = RuoYiConfig.getProfile();
        String replace = getFileUrl.replace("profile", profile);
        projectFile.setPicUrl(replace);
        OutputStream os = null;
        InputStream is = null;
        OutputStream out = null;
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        try {
            // 取得输出流
            os = response.getOutputStream();
            // 清空输出流
            response.reset();
            response.setContentType("application/x-download;charset=GBK");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(projectFile.getPicName().getBytes("utf-8"), "iso-8859-1"));
            //读取流
            File f = new File(projectFile.getPicUrl());
            byte[] byte1 =Filebyte.Filebyte(f);
            out = response.getOutputStream();
            bos = new BufferedOutputStream(out);
            System.out.println(byte1.length);
            bos.write(byte1);
            bos.flush();
        } catch (IOException e) {
            AjaxResult.error("下载附件失败,error:" + e.getMessage());
        }
        //文件的关闭放在finally中
        finally {
            try {
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {

            }
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {

            }
            try {
                if (bis != null) {
                    bis.close();
                }
            } catch (IOException e) {

            }
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {

            }
            try {
                if (os != null) {
                    os.close();
                }

            } catch (IOException e) {

            }
        }
        AjaxResult.success();
    }

    //项目图片显示
    @GetMapping("/picture/list")
    public TableDataInfo picturelist(ProjectPicture projectFile) {
        startPage();
        List<ProjectPicture> list = projectFileService.selectProjectPictureList(projectFile);
        return getDataTable(list);
    }

    //项目照片删除
    @DeleteMapping("/picture/{picIds}")
    public AjaxResult pictureremove(@PathVariable Long picIds) {
        return toAjax(projectFileService.updateProjectPicture(picIds));
    }

    /**
     * @param pfilId
     * @param response
     * @param request
     * @return
     */
    @GetMapping("/download")//下载
    public void downloadFile(@RequestParam Long pfilId, final HttpServletResponse response, final HttpServletRequest request) throws IOException {
        ProjectFile projectFile = projectFileService.selectProjectFileById(pfilId);
        String profile = RuoYiConfig.getProfile();
        int a = 0;
        String getFileUrl = projectFile.getFileUrl();
        String replace = getFileUrl.replace("profile", profile);
        projectFile.setFileUrl(replace);
        OutputStream os = null;
        InputStream is = null;
        OutputStream out = null;
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        int bytes = 0;
        try {
            // 取得输出流
            os = response.getOutputStream();
            // 清空输出流
            response.reset();
            response.setContentType("application/x-download;charset=GBK");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(projectFile.getFileName().getBytes("utf-8"), "iso-8859-1"));
            //读取流
            File f = new File(projectFile.getFileUrl());
            byte[] byte1 = Filebyte.Filebyte(f);
            out = response.getOutputStream();
            bos = new BufferedOutputStream(out);
            bos.write(byte1);
            bos.flush();
        } catch (IOException e) {
            AjaxResult.error("下载附件失败,error:" + e.getMessage());
        }
        //文件的关闭放在finally中
        finally {
            try {
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {

            }
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {

            }
            try {
                if (bis != null) {
                    bis.close();
                }
            } catch (IOException e) {

            }
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {

            }
            try {
                if (os != null) {
                    os.close();
                }

            } catch (IOException e) {

            }
        }
        AjaxResult.success();
    }

    //文件转数组

}
